# 1.导包；
import sys
import rclpy
from rclpy.node import Node
from rclpy.logging import get_logger
from base_interfaces_demo.srv import AddInts

# 3.定义节点类；
class AddIntsClient(Node):

    def __init__(self):
        super().__init__('client_py')
        # 3-1.创建客户端；
        self.client = self.create_client(AddInts, 'add_ints')
        self.get_logger().info('客户端创建了...')
        # 3-2.等待服务连接；
        while not self.client.wait_for_service(1.0):
            self.get_logger().info('服务连接中，请稍候...')

    # 3-3.组织请求数据并发送；
    def send_request(self):
        request = AddInts.Request()
        request.num1 = int(sys.argv[1])
        request.num2 = int(sys.argv[2])
        self.future = self.client.call_async(request)
    # 处理响应)
        rclpy.spin_until_future_complete(self,self.future)
        try:
            response = self.future.result()
            self.get_logger().info(
            '响应结果： %d + %d = %d' %
            (request.num1, request.num2, response.sum))
        except Exception :
            self.get_logger().info('服务请求失败：')


def main():
    if len(sys.argv)!=3:
        get_logger("rlcpy").error("请输入两个整型数据")
        return
    # 2.初始化 ROS2 客户端；
    rclpy.init()

    # 4.创建对象并调用其功能；
    addintsclient = AddIntsClient()
    addintsclient.send_request()
    
    rclpy.spin(addintsclient)

    # 5.释放资源。
    rclpy.shutdown()


if __name__ == '__main__':
    main()